// 基础JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initializeTooltips();
    initializeFileUpload();
    initializeFormValidation();
    initializeAjaxForms();
});

// 初始化工具提示
function initializeTooltips() {
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// 初始化文件上传功能
function initializeFileUpload() {
    const uploadArea = document.getElementById('upload-area');
    const fileInput = document.getElementById('file-input');
    
    if (uploadArea && fileInput) {
        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', function() {
            fileInput.click();
        });
        
        // 拖拽上传
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            uploadArea.classList.add('dragover');
        }
        
        function unhighlight() {
            uploadArea.classList.remove('dragover');
        }
        
        // 处理文件拖放
        uploadArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            fileInput.files = files;
            updateFileList(files);
        }
        
        // 文件选择变化
        fileInput.addEventListener('change', function() {
            updateFileList(this.files);
        });
    }
}

// 更新文件列表显示
function updateFileList(files) {
    const fileList = document.getElementById('file-list');
    if (!fileList) return;
    
    fileList.innerHTML = '';
    
    if (files.length === 0) {
        fileList.innerHTML = '<p class="text-muted">未选择文件</p>';
        return;
    }
    
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item mb-2';
        
        const fileInfo = document.createElement('div');
        fileInfo.className = 'd-flex justify-content-between align-items-center';
        
        const fileName = document.createElement('div');
        fileName.textContent = file.name;
        
        const fileSize = document.createElement('div');
        fileSize.className = 'text-muted small';
        fileSize.textContent = formatFileSize(file.size);
        
        fileInfo.appendChild(fileName);
        fileInfo.appendChild(fileSize);
        fileItem.appendChild(fileInfo);
        fileList.appendChild(fileItem);
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 初始化表单验证
function initializeFormValidation() {
    // Bootstrap表单验证
    const forms = document.querySelectorAll('.needs-validation');
    
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            form.classList.add('was-validated');
        }, false);
    });
}

// 初始化AJAX表单
function initializeAjaxForms() {
    const ajaxForms = document.querySelectorAll('.ajax-form');
    
    ajaxForms.forEach(form => {
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            
            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading me-2"></span>处理中...';
            
            // 收集表单数据
            const formData = new FormData(form);
            
            // 发送AJAX请求
            fetch(form.action, {
                method: form.method,
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 成功处理
                    showAlert(data.message || '操作成功', 'success');
                    
                    // 如果有重定向URL，则跳转
                    if (data.redirect) {
                        window.location.href = data.redirect;
                    }
                } else {
                    // 错误处理
                    showAlert(data.message || '操作失败', 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('发生错误，请稍后再试', 'danger');
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });
    });
}

// 显示提示消息
function showAlert(message, type = 'info') {
    const alertContainer = document.getElementById('alert-container');
    if (!alertContainer) return;
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alert.style.cssText = 'top: 20px; right: 20px; z-index: 1050; max-width: 350px;';
    
    // 根据类型选择图标
    let icon = '';
    let title = '';
    
    switch(type) {
        case 'success':
            icon = 'fa-check-circle';
            title = '成功';
            break;
        case 'danger':
            icon = 'fa-exclamation-triangle';
            title = '错误';
            break;
        case 'warning':
            icon = 'fa-exclamation-circle';
            title = '警告';
            break;
        default:
            icon = 'fa-info-circle';
            title = '提示';
    }
    
    alert.innerHTML = `
        <div class="d-flex align-items-center">
            <i class="fas ${icon} fa-2x me-3"></i>
            <div>
                <h6 class="alert-heading mb-1">${title}</h6>
                <p class="mb-0">${message}</p>
            </div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    alertContainer.appendChild(alert);
    
    // 自动关闭提示
    setTimeout(() => {
        alert.classList.remove('show');
        setTimeout(() => {
            if (alert.parentNode) {
                alert.parentNode.removeChild(alert);
            }
        }, 300);
    }, 5000);
}

// 删除文件
async function deleteFile(fileId) {
    if (!confirm('确定要删除这个文件吗？此操作不可撤销。')) {
        return;
    }
    
    try {
        const response = await fetch(`/profile/files/${fileId}`, {
            method: 'DELETE',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            // 尝试移除文件元素
            const fileElement = document.getElementById(`file-${fileId}`);
            if (fileElement) {
                // 添加淡出动画
                fileElement.style.transition = 'opacity 0.5s';
                fileElement.style.opacity = '0';
                
                setTimeout(() => {
                    fileElement.remove();
                    
                    // 检查是否还有文件
                    const fileRows = document.querySelectorAll('#files-table tbody tr');
                    if (fileRows.length === 0) {
                        const tableBody = document.querySelector('#files-table tbody');
                        tableBody.innerHTML = `
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="fas fa-folder-open fa-3x mb-3 d-block"></i>
                                    暂无文件，请上传新文件
                                </td>
                            </tr>
                        `;
                    }
                }, 500);
            } else {
                // 如果找不到元素，重新加载页面
                setTimeout(function() { 
                    window.location.reload(); 
                }, 1000);
            }
            
            // 显示成功消息
            showAlert('文件已成功删除', 'success');
        } else {
            showAlert(data.message || '删除文件失败', 'danger');
        }
    } catch (error) {
        console.error('删除文件出错:', error);
        showAlert('删除文件时发生错误，请重试', 'danger');
    }
}

// 图片预览
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    if (!preview) return;
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        
        reader.onload = function(e) {
            preview.src = e.target.result;
        };
        
        reader.readAsDataURL(input.files[0]);
    }
}

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        showAlert('已复制到剪贴板', 'success');
    }, function() {
        showAlert('复制失败，请手动复制', 'danger');
    });
}

// 确认对话框
function confirmAction(message, callback) {
    if (confirm(message)) {
        callback();
    }
}